<?php
namespace Summer\Shop\Models;

use \Backend\Models\ExportModel;
use Input;
use Config;
use Winter\Storm\Support\Collection;

class OrderExport extends ExportModel {
    protected $fillable = [
        'start_date',
        'end_date',
    ];
    public function exportData($columns, $sessionKey = null)
    {
        if(Input::has('ExportOptions')){
            $filter=Input::get('ExportOptions');
            $start_date=$filter['start_date'];
            $end_date=$filter['end_date'];
            $status_slug=$filter['status_slug'];
        }
        $query=OrderModel::select();
        if($start_date){
            $query->where('created_at','>',$start_date);
        }
        if($end_date){
            $query->where('created_at','<',$end_date);
        }
        if($status_slug){
            $query->where('status_slug',$status_slug);
        }
        $order_status_slug=Config::get('summer.shop::order_status_slug');
        $records = $query->get();
        $records->each(function($record) use ($columns,$order_status_slug) {
            $record->order_sn='【'.$record->order_sn.'】';
            $record->target_username=$record->target->username??'暂无';
            $record->target_userphone=$record->target->userphone??'暂无';
            $products='';
            foreach ($record->items as $item){
                $product_name=$item->name??'';
                $product_description=$item->description??'';
                $product_price=$item->price??'';
                $product_quantity=$item->quantity??'';
                $product='名称:'.$product_name.'规格:'.$product_description.'价格:'.$product_price.'数量'.$product_quantity;
                if($products==''){
                    $products=$product;
                }else{
                    $products.='|'.$product;
                }
            }
            $record->items_text=$products;
            $record->status_slug=$order_status_slug[$record->status_slug]['title'];
            $record->user_address=$record->user_address['consignee'].$record->user_address['phone'].$record->user_address['province_name'].$record->user_address['city_name'].$record->user_address['area_name'].$record->user_address['address'];
            $record->addVisible($columns);
        });
        return $records->toArray();
    }

    /**
     * 订单状态
     * @return mixed
     */
    public function getStatusSlugOptions()
    {
        $order_status_slug=Config::get('summer.shop::order_status_slug');
        $collection = new Collection($order_status_slug);
        return $collection->pluck('title','slug')->toArray();
    }

}
